import inspect
import os
import pygame
from PIL import Image
from typing import List


# gif动画类
class gif_frame:

    def __init__(self, git_path: str, scale: int = None):
        self.frames: List[pygame.Surface] = []
        self.frames_len = 0
        self.index = 0
        self.load_gif_frames(
            "{}/{}".format(self.get_caller_directory(), git_path), scale
        )
        self.duration = 0

    def get_caller_directory(self) -> str:
        # 获取调用栈
        stack = inspect.stack()

        # 获取调用该模块的帧
        caller_frame = stack[2]

        # 获取调用者的文件路径
        caller_file = caller_frame.filename

        # 获取调用者文件所在的目录
        return os.path.dirname(os.path.abspath(caller_file))

    def load_gif_frames(self, gif_path, scale: int = None):
        gif = Image.open(gif_path)
        duration = 0
        try:
            while True:
                frame = gif.copy()
                frame = frame.convert("RGBA")
                frame = frame.resize(
                    [int(i * scale) for i in frame.size] if scale else frame.size
                )
                self.frames.append(
                    pygame.image.fromstring(
                        frame.tobytes(),
                        frame.size,
                        frame.mode,
                    )
                )
                duration += gif.info.get("duration", 0) / 1000

                gif.seek(gif.tell() + 1)
        except EOFError:
            pass
        self.duration = duration
        self.frames_len = len(self.frames)

    def action(self):
        index = self.index
        self.index = (self.index + 1) % self.frames_len
        return self.frames[index]
